<template>
  <div ref="codemirrorContainer" class="codemirror-container"></div>
</template>

<script>
import CodeMirror from 'codemirror';
import 'codemirror/lib/codemirror.css';
import 'codemirror/theme/material.css'; // 示例：引入主题
import 'codemirror/addon/hint/show-hint.css'; // 提示样式
import 'codemirror/mode/javascript/javascript'; // 示例：引入JavaScript模式
import 'codemirror/addon/hint/show-hint'; // 引入提示插件
import 'codemirror/addon/hint/javascript-hint'; // JavaScript代码提示

export default {
  name: 'CodeMirrorEditor',
  props: {
    value: {
      type: String,
      default: ''
    },
    options: {
      type: Object,
      default() {
        return {
          lineNumbers: true,
          mode: 'javascript',
          theme: 'material'
        };
      }
    }
  },
  data() {
    return {
      editor: null
    };
  },
  mounted() {
    this.initCodeMirror();
  },
  methods: {
    initCodeMirror() {
      this.editor = CodeMirror(this.$refs.codemirrorContainer, {
        value: this.value,
        ...this.options,
        extraKeys: {
          'Ctrl-Space': 'autocomplete' // 绑定快捷键Ctrl+Space来触发代码提示
        }
      });

      // 设置 ready 事件，CodeMirror 初始化完成后触发
      this.editor.on('changes', () => {
        if (!this.editor) return;

        // 假设 'ready' 是我们定义的自定义事件
        this.$emit('ready', this.editor);
      });

      // 监听 CodeMirror 内容变化
      this.editor.on('change', (cm) => {
        this.$emit('input', cm.getValue());
      });
    }
  }
};
</script>

<style scoped>
.codemirror-container {
  height: 100%;
}
</style>
